<template>
  <!-- 弹幕聊天区域 -->
  <view class="chat-panel">
    <!-- 弹幕消息区域 -->
    <view class="message-panel" ref="messagesContainer">
      <view class="message" v-for="(msg, index) in messages" :key="index">
        <view class="message-avatar" v-if="msg.avatar">
          <image :src="msg.avatar" mode="aspectFill"></image>
        </view>
        <view class="message-content" :class="{ 'highlight': msg.highlight }">
          <!-- 添加用户名字 -->
          <span v-if="msg.nickname">{{ msg.nickname }}: </span>
          {{ msg.content }}
        </view>
      </view>
    </view>
    <!-- 底部控制栏 -->
    <view class="control-panel">
      <!-- 输入框和发送按钮 -->
      <view class="message-input">
        <input v-model="newMessage" placeholder="输入消息" class="message-input-text" ref="input"/>
        <button @click="sendMessage">发送</button>
      </view>
      <!-- 控制按钮 -->
      <view class="control-actions">
        <view class="control-item">
          <text class="fas fa-gift"></text>
          <view>礼物</view>
        </view>
        <view class="control-item">
          <text class="fas fa-shopping-bag"></text>
          <view>商品</view>
        </view>
        <view class="control-item">
          <text class="fas fa-ellipsis-h"></text>
          <view>更多</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "WorldChatBox",
  props: {
    // 新增：接收订阅地址和发送地址的props
    subscribeTopic: {
      type: String,
      default: "/game/message"
    },
    sendTopic: {
      type: String,
      default: "/mori/message"
    },
    // 新增：支持通过props配置宽高和背景色
    boxWidth: {
      type: [String, Number],
      default: 220
    },
    boxHeight: {
      type: [String, Number],
      default: 260
    },
    boxBackgroundColor: {
      type: String,
      default: 'rgba(0, 0, 0, 0.5)'
    },
    boxClass: {
      type: String,
      default: ''
    }
  },
  computed: {
    boxStyle() {
      return {
        width: typeof this.boxWidth === 'number' ? `${this.boxWidth}px` : this.boxWidth,
        height: typeof this.boxHeight === 'number' ? `${this.boxHeight}px` : this.boxHeight,
        backgroundColor: this.boxBackgroundColor
      }
    }
  },
  data() {
    return {
      messages: [],
      newMessage: "",
      clientObj: client,
      scrollThreshold: 150,
      userInfo: null
    };
  },
  mounted() {
    this.userInfo = uni.getStorageSync("userInfo");
    this.initSocket();
    this.focusInput();
  },
  methods: {
    focusInput() {
      uni.createSelectorQuery().in(this).select('.message-input').node().exec((res) => {
        const inputRef = res[0]?.node;
        if (inputRef) inputRef.focus();
      });
    },
    initSocket() {
      console.log("初始化WebSocket连接");
      // 使用props中的订阅地址
      this.clientObj.subscribe(this.subscribeTopic, (msg) => {
        try {
          const data = JSON.parse(msg.body);
          data.isSelf = this.userInfo?.id === data.id;
          this.messages.push(data);

          //如果大于20条就移除之前的信息
          if (this.messages.length > 25) {
            this.messages.shift();
          }

          this.$nextTick(() => this.scrollToBottomIfNeeded());

        } catch (error) {
          console.error("解析消息失败:", error);
        }
      });
    },
    sendMessage() {
      const content = this.newMessage.trim();
      if (!content) return;

      const message = {
        code: 1,
        id: this.userInfo?.id,
        avatar: this.userInfo?.avatar || '',
        nickname: this.userInfo?.nickname || '匿名用户',
        level: this.userInfo?.level || 1,
        gender: this.userInfo?.sex,
        content
      };
      console.log(message);
      try {
        this.clientObj.send(this.sendTopic, {}, JSON.stringify(message));
        // 将当前用户发送的消息添加到 messages 数组中
        // this.messages.push({...message, isSelf: true });
        // 如果消息数量超过25条，移除最早的消息
        if (this.messages.length > 25) {
          this.messages.shift();
        }
        this.newMessage = "";
        this.$nextTick(() => this.scrollToBottomIfNeeded());
        setTimeout(() => this.focusInput(), 100);
      } catch (error) {
        console.error("发送消息失败:", error);
        // 可以添加失败提示
      }
    },
    getGenderImage(gender) {
      if (gender === "男") return "https://img.icons8.com/color/48/000000/male.png";
      if (gender === "女") return "https://img.icons8.com/color/48/000000/female.png";
      return "";
    },
    scrollToBottomIfNeeded() {
      const container = this.$refs.messagesContainer?.$el || this.$refs.messagesContainer;
      if (!container) return;

      const { scrollHeight, clientHeight, scrollTop } = container;
      const distanceFromBottom = scrollHeight - scrollTop - clientHeight;

      if (distanceFromBottom <= this.scrollThreshold) {
        container.scrollTop = scrollHeight;
      }
    }
  }
};
</script>

<style scoped>
/* 引入live.vue中的样式 */
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');

/* 弹幕聊天区域 */
.chat-panel {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 10;
  display: flex;
  flex-direction: column;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
}

/* 弹幕消息区域 */
.message-panel {
  width: 100%;
  max-height: 200px;
  overflow: hidden;
  margin-bottom: 10px;
}
.message {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  animation: messageFadeIn 0.3s ease-out;
}
.message-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 8px;
  flex-shrink: 0;
}
.message-avatar image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.message-content {
  background: rgba(0, 0, 0, 0.4);
  padding: 6px 12px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.4;
  max-width: 80%;
}
.message-content.highlight {
  background: rgba(255, 59, 119, 0.4);
}

/* 底部控制栏 */
.control-panel {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.message-input {
  flex: 1;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  padding: 4px 8px;
  height: 50px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin: 0px 10px;
}
.message-input-text {
  background: transparent;
  border: none;
  border-radius: 0;
  height: auto;
  width: 100%;
  align-items: center;
  margin-right: 5px;
  font-size: 1em;
  color: white;
  outline: none;
}
.message-input button {
  margin-left: 10px;
  width: 90px;
  height: 45px;
  background: linear-gradient(to right, #ff3b77, #ff6b9c);
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: bold;
}
.control-actions {
  display: flex;
  align-items: center;
}
.control-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-left: 20px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.9);
}
.control-item text {
  font-size: 24px;
  margin-bottom: 4px;
}

/* 动画定义 */
@keyframes messageFadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 适配不同屏幕尺寸 */
@media (max-height: 700px) {
  .chat-panel {
    padding-bottom: 20px;
  }
  .message-input-text {
    height: 5vh;
  }
}
</style>